package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.otw.common.OtwConstant;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.otw.dto.DeliveryOrderCreateCallbackDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.Result;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpTokenUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.IntegrateUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapif042v2.dto.DeliveryOrderCreateCallbackRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapif042v2.service.MnSapIf042V2Service;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MnSapIf042Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommSDO;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * SAP 交货单创建call back接口F-B、B-b
 * sap -> 中台
 * @author baizhuo
 * @version 1.0
 * @date 2023/12/30 13:40
 */
@Component
@Primary
public class MnSapIf042V2ServiceImpl implements MnSapIf042V2Service {

    private final Log log = Log.getLogger(MnSapIf042V2ServiceImpl.class);

    @Autowired
    private HttpUtils httpUtils;

    @Override
    @ProcessInvoker(remark = "MnSapIf042V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public MnSapCommResponse deliveryOrderCreateCallback(DeliveryOrderCreateCallbackRequest deliveryOrderCreateCallbackRequest) {
        /**
         *
         {
         "hEADER":{
         "interfacePath":"/RESTAdapter/ZTOFC/ECC/JHD_Creat",
         "messageId":"7e587491-6b48-40bf-bfdd-41c903be5cd8",
         "receiver":"YWZT",
         "sendTime":"00:33:01.340",
         "sender":"ECC"
         },
         "iTEM1":[
         {
         "dREF1":"DN20231102005004",
         "fLAG":"S",
         "mESSAGE":"S成功生成交货单",
         "vBELN":"0826907140",
         "vBELV":"1022722021"
         }
         ]
         }
         */
        log.info("MnSapIf042V2Service deliveryOrderCreateCallback param:{}", JSON.toJSONString(deliveryOrderCreateCallbackRequest));
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
        MnSapIf042Request mnSapIf042Request = IntegrateUtils.safeGetMessageObject(MnSapIf042Request.class);
        try {
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            String urlPrefix = OtsApplicationAdapterSdkConstants.urlPrefix();
            String url = urlPrefix + "api/mn_bc_link/sap042detail";
            JSONObject messageJson = JSON.parseObject(deliveryOrderCreateCallbackRequest.getMessage());
            //JSONArray jsonArray = messageJson.getJSONArray("ITEM1");
            //List<DeliveryOrderCreateCallbackDTO> param = new ArrayList<>();
            //for (int i = 0; i < jsonArray.size(); i++) {
            //    JSONObject jsonObject = jsonArray.getJSONObject(i);
            //    DeliveryOrderCreateCallbackDTO deliveryOrderCreateCallbackDTO = new DeliveryOrderCreateCallbackDTO();
            //    deliveryOrderCreateCallbackDTO.setDref1((String) jsonObject.get("DREF1"));
            //    deliveryOrderCreateCallbackDTO.setFlag((String) jsonObject.get("FLAG"));
            //    deliveryOrderCreateCallbackDTO.setMessage((String) jsonObject.get("MESSAGE"));
            //    deliveryOrderCreateCallbackDTO.setVbeln((String) jsonObject.get("VBELN"));
            //    if(Objects.nonNull(jsonObject.get("VBELV"))){
            //        deliveryOrderCreateCallbackDTO.setVbelv(String.valueOf(jsonObject.get("VBELV")));
            //    }
            //    if (jsonObject.containsKey("ITEM2")) {
            //        deliveryOrderCreateCallbackDTO.setItem2(jsonObject.getJSONArray("ITEM2").toJSONString());
            //    }
            //    param.add(deliveryOrderCreateCallbackDTO);
            //}
            messageJson.put("key", messageJson.getJSONObject("HEADER").getString("MESSAGEID"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", messageJson.toJSONString());
            log.info(
                "MnSapIf042V2ServiceImpl deliveryOrderCreateCallback call bc link interface,url:{}, header:{}, "
                    + "param:{}",
                url, header, JSON.toJSONString(jsonObject));
            ResponseEntity<Result> post = httpUtils.post(url, header, jsonObject, Result.class);
            Result result = post.getBody();
            log.info("MnSapIf042V2ServiceImpl deliveryOrderCreateCallback result:{}", JSON.toJSONString(result));
            if (result.isSuccess()) {
                mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            } else {
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setErrCode(result.getErrorCode());
                mnSapCommSDO.setMessage(result.getMessage());
            }
        } catch (Exception e) {
            log.error("call bc-link inOutBoundOrderCreate error", e);
            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
            mnSapCommSDO.setErrCode(OtwConstant.ORDER_001_01_01_001);
            mnSapCommSDO.setMessage(MnSAPStatus.ERROR.getMsg());
        }
        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
        return mnSapCommResponse;
    }
}
